import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;

import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class SavePanel extends JPanel {

	JTextField path;
	
	private JFileChooser fc;
	
	public File getFile()
	{
		File file=new File(path.getText());
		if(!file.exists() || !file.isDirectory())
		{
			JOptionPane.showMessageDialog(Main.mainFrame, "Chosen world folder is incorrect!");
			return null;
		}
		
		return file;
	}
	
	public SavePanel()
	{		
		
		setBorder(BorderFactory.createTitledBorder("Choose world folder: "));
		
		JLabel label = new JLabel("World folder path: ");
		path = new JTextField();
		JButton browse = new JButton("Browse");
		JButton appdata = new JButton(".minecraft");
		
		JButton load=new JButton("Load");
		
		fc=new JFileChooser();
		fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		
		path.setPreferredSize(new Dimension(200,20));

		browse.addActionListener(new AbstractAction() {
			public void actionPerformed(ActionEvent e) {				
				int ret = fc.showOpenDialog(Main.mainFrame);
				if(ret == JFileChooser.APPROVE_OPTION)
				{
					try {
						path.setText(fc.getSelectedFile().getCanonicalPath());
					} catch (IOException e1) {						
					}
				}
			}
		});
		
		appdata.addActionListener(new AbstractAction() {
			public void actionPerformed(ActionEvent e) {
				fc.setCurrentDirectory(new File(System.getenv("appdata")+"\\.minecraft\\saves"));
				int ret = fc.showOpenDialog(Main.mainFrame);
				if(ret == JFileChooser.APPROVE_OPTION)
				{
					try {
						path.setText(fc.getSelectedFile().getCanonicalPath());
					} catch (IOException e1) {						
					}
				}
			}
		});
		
		load.addActionListener(new AbstractAction() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					Main.mainFrame.minecraft_map=new MinecraftMap(new File(path.getText()));
					Main.mainFrame.minecraft_map.getSpawnPoint();
				} catch (Exception e) {
					Main.mainFrame.minecraft_map=null;
					JOptionPane.showMessageDialog(null, "Error loading world save:\n"+e.getMessage());
					return;
				}
				
				Main.mainFrame.location_chooser.setLocation(Main.mainFrame.minecraft_map.spawnX/16,Main.mainFrame.minecraft_map.spawnZ/16);
			}
		});
		
		JPanel top=new JPanel();		
		
		top.add(label);
		top.add(path);
		top.add(browse);
		top.add(appdata);
		
		setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));
		
		add(top);		
		add(load);
	}
	
}
